package app.Insam.VNC;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import app.Insam.VNC.remote.ConnectionBean;
import app.Insam.VNC.remote.VncCanvasActivity;
import app.Insam.VNC.remote.VncConstants;


public class InsamMain extends Activity {
	public static final String TAG = "InsamApp";
	
	public static final int ACTION_PREPARE_CONNECTION = 0x1;	
	public static final int EXTRA_HOME = 0x10;
	public static final int EXTRA_OFFICE = 0x11;
		
	InsamAsyncWifiManager mWifi;
	SharedPreferences mPref;
	int mAction=0;		
	InsamConnection mConnection;
	
	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message _msg) {
//			Log.d(TAG, "handler get message:" + _msg.what);				
			switch(_msg.what) {
			case ACTION_PREPARE_CONNECTION:				
				prepareConnection();
				break;
			default:
				Log.e(TAG, "unauthorized signal");				
			}				
		}
	};	

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
//    	Toast.makeText(this, "onCreate", Toast.LENGTH_SHORT).show();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.insam_main);                
        
        mPref = PreferenceManager.getDefaultSharedPreferences(this);
        mWifi = new InsamAsyncWifiManager(this);        
        
		if(mPref.getBoolean(InsamPreferencesKey.HomePC_Use.toString(), true)==false) {
			findViewById(R.id.btnHomeConn).setEnabled(false);
		}				
		if(mPref.getBoolean(InsamPreferencesKey.OfficePC_Use.toString(), true)==false) {			
			findViewById(R.id.btnOfficeConn).setEnabled(false);
		} else {
			startService(new Intent(this, InsamService.class).addFlags(InsamService.ACTION_SCAN_LOCATION));
		}
    }
    
	public void mOnClickConn(View v) {	
		if(R.id.btnHomeConn==v.getId()) {
			mAction = EXTRA_HOME;
		}else {
			mAction = EXTRA_OFFICE;
		}
		//checkWifiState();			
		prepareConnection();			//테스트를 위해 변경
    }
	
	public void checkWifiState() {
//		Log.d(TAG, "checkWifiState");	
		switch(mAction) {
		case EXTRA_HOME:			//Home conn일 경우 와이파이 켜는지 검사	
			if(mWifi.isEnabled()==false) {	
				showDialog(R.string.text_Wifi_Off);		
				return;
			} 
			if(mWifi.isConnected(mAction)==false) {
				mWifi.connect(mAction);
				return;
			}
			break;
		case EXTRA_OFFICE:			//Office conn일 경우 회사 안에 위치하는지, 회사망에 연결되어있는지 검사(wifi 자동  on)					
			if(InsamApp.InOffice==false) {			
				showDialog(R.string.text_Rescan);
				return;
			} 
			if(mWifi.isConnected(mAction)==false) {
				mWifi.connect(mAction);
				return;
			}	
			break;		
		default:
			return;
		}
		prepareConnection();
	}	
	
	public void prepareConnection() {		
		String ip;
		int port;
		boolean keepPass;
		if(mAction == EXTRA_HOME) {
			ip = mPref.getString(InsamPreferencesKey.HomePC_IP.toString(), null);
			port = Integer.parseInt(mPref.getString(InsamPreferencesKey.HomePC_Port.toString(), getString(R.string.default_homeport)));
			keepPass = mPref.getBoolean(InsamPreferencesKey.HomePC_KeepPasswd.toString(), false);
		} else {
			ip = mPref.getString(InsamPreferencesKey.OfficePC_IP.toString(), null);
			port = Integer.parseInt(mPref.getString(InsamPreferencesKey.OfficePC_Port.toString(), getString(R.string.default_officeport)));
			keepPass = mPref.getBoolean(InsamPreferencesKey.OfficePC_AutoLogin.toString(), false);
		}	
		
		if(ip==null || ip.equals("")) {
			showDialog(R.string.text_NoSet);
			return;
		} 		
		
		mConnection = new InsamConnection(this, ip, port);	
		if(keepPass) {
			mConnection.setPassword("1234");	//수정해야함
			//mConnInfo.setKeepPassword(true);			
			connect();
		} else {
			showDialog(R.string.text_Login);
		}		
	}
	
	public void sendMessageConnect() {
		mHandler.sendEmptyMessageDelayed(ACTION_PREPARE_CONNECTION, 100);
	}
	
	public void connect() {
		if(mAction == EXTRA_HOME) {
			VncStart();
		} else {		
			String id =  mPref.getString(InsamPreferencesKey.OfficePC_ID.toString(), null);
			if(id==null || id.equals("")) {
				Toast.makeText(this, "ID is not set", Toast.LENGTH_LONG).show();//대화창으로 수정 필요할
				return;
			} 
			mConnection.ConnectServer(id);
		}
	}
	
	
	public void VncStart() {
		ConnectionBean connInfo = mConnection.connInfo();
		  	
		String color = mPref.getString(InsamPreferencesKey.ColorFormat.toString(), null);
		if(color!=null)
			connInfo.setColorModel(color);
		
		Intent intent = new Intent(this, VncCanvasActivity.class);  
    	intent.putExtra(VncConstants.CONNECTION, connInfo.Gen_getValues());   
    	
		startActivityForResult(intent,R.id.vnc_canvas);
	}
	
	@Override
	protected void onActivityResult(int _requestCode, int _resultCode, Intent _data) {
//		Log.d(TAG, "onActivityResult");			
		switch(_requestCode) {
		case R.id.itemPreference:
			if(_resultCode==RESULT_OK) {
				sendMessageConnect();
			} else {
				onFinishConnect();
			}
			if(InsamPreferences.ChangeUse) {
				findViewById(R.id.btnHomeConn).setEnabled(mPref.getBoolean(InsamPreferencesKey.HomePC_Use.toString(), true));
				findViewById(R.id.btnOfficeConn).setEnabled(mPref.getBoolean(InsamPreferencesKey.OfficePC_Use.toString(), true));
			}
			break;
		case R.id.vnc_canvas:
			if(mConnection!=null) {
				mConnection.Logout();
				mConnection=null;			
			}
			onFinishConnect();
			//실패에 따른 처리코드 추가(암호 자동설정시에 암호 실패 등..)
			break;
		}		
	}
	
	public void onFinishConnect() {
		mWifi.off();
		mAction=0;
		if(mConnection!=null) {
			mConnection=null;			
		}
	}
	
    @Override
	protected Dialog onCreateDialog(int _id) {
    	switch(_id) {    	
    	case R.string.text_Wifi_Off:
    		return new AlertDialog.Builder(this) 
    		.setTitle(R.string.HomePC_Conn)
    		.setIcon(android.R.drawable.ic_dialog_info) 
			.setMessage(_id)
			.setPositiveButton(R.string.WifiOn, new OnClickListener() {		
    			public void onClick(DialogInterface _dialog, int _whichButton) {
    				mWifi.connect(mAction);
    			}
    		})
			.setNegativeButton(R.string.Ignore, new OnClickListener() {		
    			public void onClick(DialogInterface _dialog, int _whichButton) {
    				prepareConnection();
    			}
    		})
			.create();
    		
    	case R.string.text_Rescan:
    		return new AlertDialog.Builder(this) 
    		.setTitle(R.string.OfficePC_Conn)
    		.setIcon(android.R.drawable.ic_dialog_info) 
			.setMessage(_id)
			.setPositiveButton(R.string.Rescan, new OnClickListener() {			
    			public void onClick(DialogInterface _dialog, int _whichButton) {
    				mWifi.connect(mAction);
    			}
    		})
			.setNegativeButton(android.R.string.cancel, new OnClickListener() {	
    			public void onClick(DialogInterface _dialog, int _whichButton) {
    				onFinishConnect();
    			}
    		})
			.create();
    	case R.string.text_NoSet:	
    		return new AlertDialog.Builder(this)
    		.setTitle("Need Setting")
    		.setIcon(android.R.drawable.ic_dialog_info) 
    		.setMessage(_id)
    		.setCancelable(false)
    		.setPositiveButton(android.R.string.ok,  new OnClickListener() {		
    			public void onClick(DialogInterface _dialog, int _whichButton) {
    				Intent intent = new Intent(getBaseContext(), InsamPreferences.class);
    				intent.putExtra("extra", mAction);
    			    startActivityForResult(intent, R.id.itemPreference);	
    			}
    		})    		
    		.setNegativeButton(android.R.string.cancel,new OnClickListener() {		
    			public void onClick(DialogInterface _dialog, int _whichButton) {
    				onFinishConnect();
    			}})
    		.create();
    	case R.string.text_Login:
    		final LinearLayout linear = (LinearLayout)View.inflate(this, R.layout.dlg_passwd, null);
    		
    		return new AlertDialog.Builder(this)
    		.setTitle("Login")
    		.setIcon(android.R.drawable.ic_dialog_info) 
    		.setView(linear)    
    		.setCancelable(false)
    		.setPositiveButton(R.string.Login,  new OnClickListener() {		
    			public void onClick(DialogInterface _dialog, int _whichButton) {
    				String pass = ((TextView)linear.findViewById(R.id.edit_pass)).getText().toString();
    				mConnection.setPassword(pass);
    				boolean keep = ((CheckBox)linear.findViewById(R.id.chk_keepPass)).isChecked();
    				if(keep) {
    					String key; 
    					if(mAction==EXTRA_HOME) {
    						key = InsamPreferencesKey.HomePC_KeepPasswd.toString();    						
    					} else {
    						key = InsamPreferencesKey.OfficePC_AutoLogin.toString();
    					}
    					Editor edr = mPref.edit();
    					edr.putBoolean(key, true);
    					edr.commit();
    				} /*else {
    					mConnInfo.setKeepPassword(false);
    				}  */  				
    				connect();
    			}
    		})    		
    		.setNegativeButton(android.R.string.cancel,new OnClickListener() {	
    			public void onClick(DialogInterface _dialog, int _whichButton) {
    				onFinishConnect();
    			}})
    		.create();    		
    	default:
    		return new AlertDialog.Builder(this) 
			.setTitle(R.string.Sorry)
			.setIcon(android.R.drawable.ic_dialog_info) 
			.setMessage(R.string.text_Sorry)
			.setPositiveButton(android.R.string.ok, null)
			.create();
    	}
	}
    

	@Override
	protected void onPrepareDialog(int _id, Dialog _dialog, Bundle _bdl) {
		super.onPrepareDialog(_id, _dialog);
		switch(_id) {
    	case R.string.text_NoSet:
    	case R.string.text_Login:
    		if(mAction==EXTRA_HOME) {
    			_dialog.setTitle(R.string.HomePC_Conn);    			
    		} else {
    			_dialog.setTitle(R.string.OfficePC_Conn);
    		}
			break;
		}
	}

    
	@Override
	public boolean onCreateOptionsMenu(Menu _menu) {
		getMenuInflater().inflate(R.menu.mainmenu, _menu);
		return super.onCreateOptionsMenu(_menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem _item) {
		switch(_item.getItemId()) {
		case R.id.itemPreference:
			Intent intent = new Intent(this, InsamPreferences.class);
	    	startActivityForResult(intent, R.id.itemPreference);
			break;
		case R.id.itemHelp:
			startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://code.google.com/p/insam-vnc/")));			
			break;
		case R.id.itemExit:
			finish();
			break;
		}
		return super.onOptionsItemSelected(_item);
	}

	@Override
	protected void onStart() {
//		Toast.makeText(this, "onStart", Toast.LENGTH_SHORT).show();	
		super.onStart();
	}
	
    @Override
	protected void onRestart() {
//    	Toast.makeText(this, "onRestart", Toast.LENGTH_SHORT).show();
		super.onRestart();
	}

	@Override
	protected void onResume() {
//		Toast.makeText(this, "onResume", Toast.LENGTH_SHORT).show();
		super.onResume();
	}

    @Override
	protected void onDestroy() {
 //   	Toast.makeText(this, "onDestroy", Toast.LENGTH_SHORT).show();
		super.onDestroy();
	}
}